package com.longway.common.ext.directive;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jfinal.kit.StrKit;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
import com.longway.common.constant.Const;
import com.longway.common.model.BaseMenu;
import com.longway.common.model.BaseUser;
import com.longway.common.service.BusinessService;

/**
 * #userMenus("userId","roleId")
 */
public class UserMenusDirective extends Directive {

	private Map<String,List<BaseMenu>> menuMaps = new HashMap<String,List<BaseMenu>>();
	
	private Expr userIdExpr;
	private Expr roleIdExpr;
	
	@Override
    public void exec(Env env, Scope scope, Writer writer) {
		BaseUser baseUser = (BaseUser)scope.getRootData().get(Const.loginAccountCacheName);
		if (baseUser != null && baseUser.isStatusOk()) {
			String roleId = (String)roleIdExpr.eval(scope);
			Long userId = (Long)userIdExpr.eval(scope);
			List<BaseMenu> userMenus  = BusinessService.me.getMenusByUserIdAndRoleId(userId ,roleId);
			
			for (BaseMenu baseMenu : userMenus) {
				if(menuMaps.get(baseMenu.getPCode()) == null){
					menuMaps.put(baseMenu.getPCode(), new ArrayList<BaseMenu>());
				}
				menuMaps.get(baseMenu.getPCode()).add(baseMenu);
			}
			
			StringBuilder sb = new StringBuilder();
			StringBuilder firstMenu = new StringBuilder();
			for(BaseMenu baseMenu : userMenus) {
				if (baseMenu.getLevels() == 1) {
					String subMenu = "";
					firstMenu.delete(0, firstMenu.length()); 
					String href = StrKit.isBlank(baseMenu.getUrl()) ? "#" : baseMenu.getUrl();
					String addtabs = StrKit.isBlank(baseMenu.getUrl()) ? "" : "data-addtabs=\"" + baseMenu.getCode() + "\"";
					buildPmenu(firstMenu,href,addtabs,baseMenu);
					subMenu = this.reloadMenu(userMenus, baseMenu.getCode().trim(), firstMenu.toString(), 1);// 寻找子菜单
					sb.append(subMenu);
				}
			}
			//版权校验
			/*sb.append("<script type=\"text/javascript\">");
			sb.append(" $(function(){");
			sb.append("  setTimeout(function(){");
			sb.append("  var $supporter = $(\"#support\");");
			sb.append("  $supporter.addClass('bigger-120');");
			sb.append("  var name = $supporter.html();");
			sb.append("  var index = layer;");
			sb.append("  if(index == undefined){");
			sb.append("    alert(\"该产品版权归ryc 所有,请勿盗版！\");");
			sb.append("    return;");
			sb.append("  }");
			sb.append("  if(name == undefined){");
			sb.append("    layer.alert(\"该产品版权归 ryc 所有，请勿盗版！\", {icon: 2,title:\"侵权警告\"});");
			sb.append("    return;");
			sb.append("  } else if(!(name.indexOf(\"ryc\") >= 0 && $supporter.is(\"span\") && !$supporter.is(\":hidden\"))){");
			sb.append("    layer.alert(\"该产品版权归 ryc 所有，请勿盗版！\", {icon: 2,title:\"侵权警告\"});");
			sb.append("    return;");
			sb.append("  }");
			sb.append("  }, 1800);");
			sb.append(" });");
			sb.append("</script>");*/
			
			try {
				writer.write(sb);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 从 #userMenus 指令参数中获取 userId,roleId
	 */
	@Override
    public void setExprList(ExprList exprList) {
		Expr[] exprArray = exprList.getExprArray();
		if (exprArray.length == 0) {
			throw new ParseException("#userMenus directive parameter cant not be null", location);
		}
		if (exprArray.length > 2) {
			throw new ParseException("wrong number of #userMenus directive parameter, two parameters allowed at most", location);
		}
		if (exprArray.length == 2) {
			userIdExpr = exprArray[0];
			roleIdExpr = exprArray[1];
		}
	}
	
	/**
	 * 加载子菜单
	 * 
	 * @param baseMenus
	 *            菜单集合
	 * @param pCode
	 *            父编号
	 * @param pStr
	 *            父HTML
	 * @param levels
	 *            层级
	 * @return String 返回子菜单HTML集
	 */
	public String reloadMenu(List<BaseMenu> baseMenus, String pCode, String pStr, int levels) {
			StringBuilder Str = new StringBuilder();
			String subStr = "";
			for (BaseMenu baseMenu : baseMenus) {
				int _levels = baseMenu.getLevels();
				String _code = baseMenu.getCode();
				String _pCode = baseMenu.getPCode();
				String _url = baseMenu.getUrl();
				if ((_pCode.equals(pCode) && _levels > levels)) {
					String href = StrKit.isBlank(_url) ? "#" : _url;
					String addtabs = StrKit.isBlank(_url) ? "" : "data-addtabs=\"" + _code + "\"";
					if(this.hasChildren(_code)){
						Str = buildPmenu(Str,href,addtabs,baseMenu);
					}else{
						Str = buildLmenu(Str,href,addtabs,baseMenu);
					}
					
	
					subStr = this.reloadMenu(baseMenus, _code, Str.toString(), _levels);// 递归寻找子菜单
	
					Str = StrKit.isBlank(subStr) ? Str : new StringBuilder(subStr);
				}
			}
			if (Str.length() > 0) {
				pStr += StrKit.isBlank(pStr) ? Str.toString() : "<ul class=\"treeview-menu\">" + Str.toString() + "</ul>";
				pStr += "</li>";
				return pStr;
			} else {
				return "";
			}
	}
	
	private boolean hasChildren(String code){
		if(menuMaps.get(code) != null && (menuMaps.get(code).size() > 0)){
			return true;
		}
		return false;
	}
	
	private StringBuilder buildPmenu(StringBuilder firstMenu,String href,String addtabs,BaseMenu baseMenu){
		firstMenu.append("<li class=\"treeview\">");
		firstMenu.append("	<a href=\"#\" data-url=\"" + href + "\" " + addtabs + " data-title=\"" + baseMenu.getName() + "\" data-icon=\"fa " + baseMenu.getIcon() + "\" >");
		firstMenu.append("		<i class=\"fa " + baseMenu.getIcon() + "\"></i>");
		firstMenu.append("		<span>" + baseMenu.getName() + "</span>");
		firstMenu.append("		<span class=\"pull-right-container\">");
		firstMenu.append("			<i class=\"fa fa-angle-left pull-right\"></i>");
		firstMenu.append("		</span>");
		firstMenu.append("	</a>");
		return firstMenu;
	}
	
	private StringBuilder buildLmenu(StringBuilder Str,String href,String addtabs,BaseMenu baseMenu){
		Str.append("<li>");
		Str.append("	<a href=\"#\" data-url=\"" + href + "\" " + addtabs + " data-title=\"" + baseMenu.getName() + "\" data-icon=\"fa " + baseMenu.getIcon() + "\">");
		Str.append("		<i class=\"fa " + baseMenu.getIcon() + "\"></i>");
		Str.append( baseMenu.getName());
		Str.append("	</a>");
		return Str;
	}
}